"""
auth : ginger
    云浩 : 请备注上 , 是云浩解决的加密 , 哈哈哈
    模拟实现 MeterSphere 的加密算法
    username 和 password 是加密的
"""
import base64
import rsa

__all__ = ['rsa_encrypt']

from common.do_log import do_log


def _str2key(s):
    # 对字符串解码
    b_str = base64.b64decode(s)

    if len(b_str) < 162:
        return False

    hex_str = ''

    # 按位转换成16进制
    for x in b_str:
        h = hex(x)[2:]
        h = h.rjust(2, '0')
        hex_str += h

    # 找到模数和指数的开头结束位置
    m_start = 29 * 2
    e_start = 159 * 2
    m_len = 128 * 2
    e_len = 3 * 2

    modulus = hex_str[m_start:m_start + m_len]
    exponent = hex_str[e_start:e_start + e_len]

    return modulus, exponent


def rsa_encrypt(s, pubkey_str):
    """
    rsa加密
    :param s:
    :param pubkey_str:公钥
    :return:
    """
    key = _str2key(pubkey_str)
    modulus = int(key[0], 16)
    exponent = int(key[1], 16)
    pubkey = rsa.PublicKey(modulus, exponent)
    return base64.b64encode(rsa.encrypt(s.encode(), pubkey)).decode()


def get_rsa_encrypt(input_value, rsa_key):
    value = rsa_encrypt(input_value, rsa_key)
    do_log.debug('加密键 : ' + rsa_key)
    do_log.debug('加密前 : ' + input_value)
    do_log.debug('加密后 : ' + value)
    return value


if __name__ == '__main__':

    key_res = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDlOJu6TyygqxfWT7eLtGDwajtNFOb' + \
              '9I5XRb6khyfD1Yt3YiCgQWMNW649887VGJiGr/L5i2osbl8C9+WJTeucF+S76xFxdU6' + \
              'jE0NQ+Z+zEdhUTooNRaY5nZiu5PgDB0ED/ZKBUSLKL7eibMxZtMlUDHjm4gwQco1KRMDSmXSMkDwIDAQAB'
    username = 'wu_yue'

    print('加密前 : ', username)
    print('加密后 : ', get_rsa_encrypt(username, key_res))
    print()
